package com.js.rtu.fragment.forth;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.google.gson.Gson;
import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.config.CmdConfig;
import com.js.rtu.event.StartBrotherEvent;
import com.js.rtu.fragment.forth.bd.BDBean;
import com.js.rtu.fragment.forth.bd.WriteResultBean;
import com.js.rtu.greendao.DBHelper;
import com.js.rtu.greendao.MySQLiteOpenHelper;
import com.js.rtu.greendao.db.HistoryBean;
import com.js.rtu.greendao.db.HistoryInfoBean;
import com.js.rtu.mvp.bean.Cmd02Bean;
import com.js.rtu.mvp.bean.Cmd92Bean;
import com.js.rtu.mvp.bean.base.Cmd92_H18_Bean;
import com.js.rtu.mvp.bean.base.CommonBean;
import com.js.rtu.mvp.present.Cmd09Presenter;
import com.js.rtu.mvp.present.Cmd92Presenter;
import com.js.rtu.util.BluetoothUtils;
import com.js.rtu.util.CSVUtil;
import com.js.rtu.util.CmdUtils;
import com.js.rtu.util.ExcelUtil;
import com.js.rtu.util.RxTimerUtil;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.greenrobot.greendao.annotation.Unique;

import java.io.File;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 批量补调
 * Created by zwz on 2020/4/22.
 */
public class BDFragment extends BaseFragment {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.tv_start)
    EditText tvStart;
    @BindView(R.id.tv_end)
    EditText tvEnd;
    @BindView(R.id.number_progress_bar)
    NumberProgressBar numberProgressBar;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_time2)
    TextView tvTime2;

    @BindView(R.id.tv_name)
    EditText tvName;
    @BindView(R.id.btn_set)
    TextView btnSet;

    @BindView(R.id.btn_cancel)
    TextView btnCancel;
    @BindView(R.id.tv_state)
    EditText tvState;
    @BindView(R.id.edtTime)
    EditText edtTime;
    private boolean isStop;

    private String startData;//开始时间
    private String endData;//结束时间
    private static final int type_start = 0;
    private static final int type_end = 1;


    private int curPos = 0;//当前进度
    private int maxPos = 0;//总进度
    private List<BDBean> list;//根据开始时间和结束时间以一个小时为间隔取得的补调时间集合
    private List<BDBean> successList;
    private String cmd;
    private RxTimerUtil rxTimerUtil;
    private String deviceId;


//    private List<BDBean> dataList;

//    List<Cmd92_H18_Bean> str_18H;//AI量程


    private Long operaTime;

    public static BDFragment newInstance() {
        Bundle args = new Bundle();
        BDFragment fragment = new BDFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_forth_bd;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        rxTimerUtil = new RxTimerUtil();
        initToolbarNav(toolbar);
        toolbarTitle.setText("批量补调");
        toolbar.inflateMenu(R.menu.menu_history);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                EventBus.getDefault().post(new StartBrotherEvent(HistoryListFragment.newInstance()));
                return false;
            }
        });
        Date date = new Date(System.currentTimeMillis());
        startData = new SimpleDateFormat("yy MM dd 00 00 00", Locale.CHINA).format(date);
        tvStart.setText(new SimpleDateFormat("yyyy/MM/dd 00:00:00", Locale.CHINA).format(date));
        endData = new SimpleDateFormat("yy MM dd HH 00 00", Locale.CHINA).format(date);
        tvEnd.setText(new SimpleDateFormat("yyyy/MM/dd HH:00:00", Locale.CHINA).format(date));


//      Log.e("xxxxx",   CRC16Util.Make_CRC("30 30 30 30 30 30 30 30 19 00 09 15 08 0A 06 00 00 15 08 0A 06 3B 3B"));
//      Log.e("xxxxx",   CRC16Util.Make_CRC("30 30 30 30 30 30 30 30 19 00 09 15 08 0D 00 00 00 15 08 0D 00 3B 3B"));

    }


    public static String getTimeFormatted(String time) {
        String s = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yy MM dd HH mm ss", Locale.US);
            Date d = sdf.parse(time);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US);
            s = formatter.format(d);
        } catch (Exception ex) {
            s = ex.getMessage();
        }
        return s;
    }

    public void get92Info() {
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_92);
        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                String[] data = msg.split(" ");
                if (data.length >= 12 && data[12].equals("92")) {
                    Cmd92Presenter presenter = new Cmd92Presenter();
                    CommonBean<Cmd92Bean> bean = presenter.paseData(msg);
                    Cmd92Bean cmd92Bean = bean.getData();
                    if (cmd92Bean.getStr_10H() == null) {
                        toastShow("92-获取设备ID失败");
                        return;
                    }
                    deviceId = cmd92Bean.getStr_10H();
                    if (deviceId == null) {
                        toastShow("92-获取设备ID失败");
                        return;
                    }
                    if (deviceId.isEmpty() || deviceId.equals(" ")) {
                        toastShow("92-获取设备ID失败");
                        return;
                    }
                    tvName.setText(deviceId);
                    Date date = new Date();
                    operaTime = date.getTime();
                    HistoryInfoBean infoBean = new HistoryInfoBean();
                    infoBean.setDeviceId(deviceId);
                    infoBean.setOperaTime(operaTime);
                    infoBean.setStartTime(tvStart.getText().toString());
                    infoBean.setEndTime(tvEnd.getText().toString());
                    infoBean.setInterval(edtTime.getText().toString() + "分钟");
                    infoBean.setTotal(maxPos + "");
                    infoBean.setConfig92(msg);
                    DBHelper.getInstance().getSession().getHistoryInfoBeanDao().insert(infoBean);
                    rxTimerUtil.timer(2000, new RxTimerUtil.IRxNext() {
                        @Override
                        public void doNext(long number) {

                            //5S没收到回复，再发
                            sendData08();
                        }
                    });


                }

            }

            @Override
            public void onFail(String err) {

            }
        });
    }

    /**
     * 补调
     */
    private void sendData08() {
        if (isStop) {
            return;
        }
        if (list == null || list.size() == 0)
            return;

        BDBean bdBean = list.get(curPos);
//        EE EE 30 30 30 30 30 30 30 30 19 00 09 15 08 0A 06 00 00 15 08 0A 06 3B 3B 64 00 FF FF
//        EE EE 30 30 30 30 30 30 30 30 19 00 09 15 08 0A 06 00 00 15 08 0A 06 3B 3B 04 06 FF FF

        tvTime.setText(String.format("%s", getTimeFormatted(bdBean.getStart())));
        tvTime2.setText(String.format("%s", getTimeFormatted(bdBean.getEnd())));
        String[] str_start = bdBean.getStart().split(" ");
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : str_start) {
            stringBuilder.append(String.format("%02x", Integer.parseInt(s))).append(" ");
        }
        String[] str_end = bdBean.getEnd().split(" ");
        for (String s : str_end) {
            stringBuilder.append(String.format("%02x", Integer.parseInt(s))).append(" ");
        }
        cmd = CmdUtils.getCmd(CmdConfig.CMD_09, stringBuilder.substring(0, stringBuilder.length() - 1));
        Log.e("time", "发送补调区间：" + bdBean.getStart() + "-" + bdBean.getEnd());


        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
            }

            @Override
            public void onFail(String err) {
            }
        });

    }

    /**
     * 接收的应答
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveRead(BDBean bean) {
        if (isStop){
            return;
        }
        String[] data = bean.getData().split(" ");
        if (bean.isSuccess()) {
            if (data.length <= 12) {
                return;
            }
            if (!data[12].equals("09")) {
                Log.e("xxxxxxx", bean.toString());
                return;
            }
        } else {
            //无数据的时候
            if (data.length <= 13) {
                return;
            }
            if (!data[13].equals("09")) {
                return;
            }
//            EE EE 30 30 30 30 30 30 30 31 0F 00 FE 09 04 AC F1 FF FF
        }
        retryNumber = 0;
        rxTimerUtil.cancel();
        if (curPos==list.size()){
            return;
        }
        BDBean bdBean = list.get(curPos);
        curPos++;
        successList.add(new BDBean(bdBean.getStart(), bdBean.getEnd(), bean.getData()));
        numberProgressBar.setProgress(curPos);
        Log.e("time", "成功：" + successList.size() + "/" + maxPos);
        Log.e("time", "data：" + bean.getData());
        tvState.setText(bean.isSuccess() ? "补调成功" : "当前时间区间无数据");
//        dataList.add(bean);
        new Thread(new Runnable() {
            @Override
            public void run() {
                HistoryBean historyBean = new HistoryBean();
                historyBean.setStartTime(String.format("%s", getTimeFormatted(bdBean.getStart())));
                historyBean.setEndTime(String.format("%s", getTimeFormatted(bdBean.getEnd())));
                historyBean.setIsSuccess(bean.isSuccess());
                historyBean.setData(bean.getData());
                historyBean.setPos(curPos);
                historyBean.setTime(operaTime);


                DBHelper.getInstance().getSession().getHistoryBeanDao().insert(historyBean);


                if (curPos != 0 && curPos == maxPos) {
                    EventBus.getDefault().post("已连接");//开始心跳
//                        exportExcel(dataList);
                }

            }
        }).start();


        if (curPos >= maxPos) {
            btnSet.setText("开始");
            btnCancel.setVisibility(View.GONE);
            return;
        }

        sendData08();

    }

    private int retryNumber;

    /**
     * 接收发送情况
     * N秒没收回复就再发
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveWrite(WriteResultBean bean) {
        if (isStop){
            return;
        }
        if (retryNumber >= 10) {
            tvState.setText("设备连接异常，请重启终端");
            btnSet.setText("开始");
            btnCancel.setVisibility(View.GONE);
            return;
        }
        if (!bean.isResult()) {
            //失败
            retryNumber++;
            sendData08();
        } else {
            if (curPos >= maxPos) {
                return;
            }
            retryNumber++;
            rxTimerUtil.timer(2000, new RxTimerUtil.IRxNext() {
                @Override
                public void doNext(long number) {
                    if (curPos >= maxPos) {
                        return;
                    }
                    //5S没收到回复，再发
                    sendData08();
                }
            });
        }
        tvState.setText("2S无应答,重试第" + retryNumber + "次");

    }

    @OnClick({R.id.tv_start, R.id.tv_end, R.id.btn_set})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_start:
                showDialog(type_start, tvStart);
                break;
            case R.id.tv_end:
                showDialog(type_end, tvEnd);
                break;
            case R.id.btn_cancel:
                isStop = true;
                break;
            case R.id.btn_set:
                if (edtTime.getText().toString().isEmpty()) {
                    toastShow("请输入自定义补调间隔");
                    return;
                }
                if (startData.equals(endData)) {
                    toastShow("开始时间、结束时间不能一样");
                    return;
                }

                list = getList(startData, endData);
                for (BDBean bdBean : list) {
                    Log.e("11111", bdBean.toString());
                }


                successList = new ArrayList<>();
                curPos = 0;
                maxPos = list.size();
                if (maxPos == 0) {
                    return;
                }
                numberProgressBar.setProgress(curPos);
                numberProgressBar.setMax(maxPos);
//                dataList = new ArrayList<>();
//                str_18H = new ArrayList<>();
                btnSet.setText("补调中..");
                EventBus.getDefault().post("BD补调");//停止心跳
                isStop = false;
                btnCancel.setVisibility(View.VISIBLE);
                get92Info();
                break;
        }
    }


    /**
     * 时间选择
     */
    private void showDialog(final int type, TextView textView) {
        TimePickerView pvTime = new TimePickerBuilder(_mActivity, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                switch (type) {
                    case type_start:
                        startData = new SimpleDateFormat("yy MM dd HH mm 00", Locale.CHINA).format(date);
                        textView.setText(new SimpleDateFormat("yyyy/MM/dd HH:mm:00", Locale.CHINA).format(date));
                        break;
                    case type_end:
                        endData = new SimpleDateFormat("yy MM dd HH mm 00", Locale.CHINA).format(date);
                        textView.setText(new SimpleDateFormat("yyyy/MM/dd HH:mm:00", Locale.CHINA).format(date));
                        break;
                }

            }
        }).setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setTitleSize(20)//标题文字大小
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.show();
    }

    /**
     * 根据所选时间，按一个小时一组分组
     *
     * @param start
     * @return
     */
    private List<BDBean> getList(String start, String endData) {
        List<BDBean> list = new ArrayList<>();
        String mStartTime = start;
        for (int i = 10000000; i > 0; i--) {
            SimpleDateFormat format = new SimpleDateFormat("yy MM dd HH mm ss", Locale.CHINA);//返回数据时间的格式
            Date data = null;
            Date end = null;
            try {
                data = format.parse(mStartTime);
                end = format.parse(endData);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            if (data == null || end == null) {
                break;
            }
            if (!data.before(new Date())) {
                break;
            }
            if (!data.before(end)) {
                break;
            }
            Calendar cal = Calendar.getInstance();
            cal.setTime(data);

            cal.add(Calendar.MINUTE, Integer.parseInt(edtTime.getText().toString()));
            data = cal.getTime();
            String Str_end = format.format(data);
            String Str_start = mStartTime;
            mStartTime = format.format(data);
            try {
                Date curEndDate = format.parse(Str_end);
                if (data.after(curEndDate)) {
                    Str_end = format.format(end);
                }
            } catch (ParseException pE) {
                pE.printStackTrace();
            }


//            //结束时间和当前时间相比
//            if (!data.before(new Date())) {
//                break;
//            }
//            //结束时间和结束时间相比
//            if (!data.before(end)) {
//                break;
//            }
            list.add(new BDBean(Str_start, Str_end));
        }
        return list;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        rxTimerUtil.cancel();
        isStop = true;
        EventBus.getDefault().unregister(this);
    }

}
